/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bef.core.action.variable;

import com.inspur.edp.bef.api.action.VoidActionResult;
import com.inspur.edp.bef.api.be.IBEManagerContext;
import com.inspur.edp.bef.core.action.base.ActionStack;
import com.inspur.edp.bef.core.be.BEManager;
import com.inspur.edp.bef.core.be.BEManagerContext;
import com.inspur.edp.bef.core.session.BEFuncSessionBase;
import com.inspur.edp.bef.core.session.FuncSessionManager;
import com.inspur.edp.commonmodel.core.variable.VarBufferManager;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.variable.api.data.IVariableData;
import com.inspur.edp.cef.variable.api.manager.IVariableManager;
import com.inspur.edp.cef.variable.api.variable.IVariable;

public class VariableModifyMgrAction extends AbstractManagerAction<VoidActionResult> {

  private IChangeDetail changeDetail;

  public VariableModifyMgrAction(IBEManagerContext managerContext, IChangeDetail changeDetail) {
    this.changeDetail = changeDetail;
  }

  private IVariableManager getVarManager() {
    return ((BEManagerContext) this.getBEManagerContext()).getVariableManager();
  }

  private VarBufferManager getVarBufferManager() {
    return ((BEManagerContext) this.getBEManagerContext()).getVarBufferManager();
  }

  @Override
  public final void execute() {
    if (getVarManager() == null) {
      return;
    }
    IVariableData data = getVarBufferManager().getCurrentData();
    Object tempVar = getVarManager().createValueObject(data);
    IVariable variableEntity = (IVariable) ((tempVar instanceof IVariable) ? tempVar : null);
    getVarBufferManager().Listener().suspend();
    try {
      variableEntity.modify(changeDetail);
      if (!ActionStack.isLastNode()) {
        ((BEManager) this.getBEManagerContext().getBEManager()).getResponseContext()
            .mergeVarInnerChange(changeDetail);
      }
      if (variableEntity.getVariableContext().getInnerChange() != null) {
        ((BEManager) this.getBEManagerContext().getBEManager()).getResponseContext()
            .mergeVarInnerChange(variableEntity.getVariableContext().getInnerChange());
      }
    } finally {
      getVarBufferManager().Listener().resume();
    }
  }
}
